package com.alpaca.recommend.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * spring loader
 *
 * @author 宇翔
 */
public class SpringContextLoader implements ApplicationContextAware{


    // Spring 上下文对象
    private static ApplicationContext context;


    // 配置文件路径
    private static final String CONFIG_FILE_LOCATION = "classpath:application-context.xml";


    public static void init() {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{CONFIG_FILE_LOCATION});
        context.start();
        SpringContextLoader.context = context;
    }

    /**
     * 取得spring环境的Bean
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
        return context.getBean(beanName);
    }

    public static <T> T getBean(Class<T> clazz) {
        return context.getBean(clazz);
    }

    public static boolean isBeanExist(String beanname) {
        return context.containsBean(beanname);
    }

    @Override
    public  void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextLoader.context = applicationContext;
    }
}
